<?php
require_once(ABSPATH . '/wp-includes/media.php');
require_once(ABSPATH . '/wp-admin/includes/image.php');
//Use Cufon for titles on the page.
function add_cufon(){
?>
	<script src="<?php bloginfo('stylesheet_directory') ?>/js/cufon-yui.js" type="text/javascript"></script>
	<script src="<?php bloginfo('stylesheet_directory') ?>/js/Vegur_400.font.js" type="text/javascript"></script>
	<script type="text/javascript">
		Cufon.replace('#blog-title a',{ hover: true })('.menu a', { hover: true })('.aside h3')('h1.entry-title')('h1.page-title')('h2.entry-title',{ hover: true});
	</script>
<?php
}
add_action('wp_head', 'add_cufon');
function add_cufon_iefix(){
?>
	<script type="text/javascript"> Cufon.now(); </script>
<?php 
}
add_action('wp_footer', 'add_cufon_iefix');

//Use Cufon for titles on the page.
function unreg_sidebar(){
	unregister_sidebar_widget('Meta');
}
add_action( 'widget_init', 'unreg_sidebar' );

/* ********************************************** */
/* Add an options pannel for your Thematic Child Theme
/* ********************************************** */

// ---------- "Child Theme Options" menu STARTS HERE

add_action('admin_menu' , 'childtheme_add_admin');
function childtheme_add_admin() {
	add_submenu_page('themes.php', 'Street Theme Options', 'Street Theme Options', 'edit_themes', basename(__FILE__), 'childtheme_admin');
}

function childtheme_admin() {
	
	$child_theme_image = get_option('child_theme_image');
	$enabled = get_option('child_theme_logo_enabled');
	
	if ($_POST['options-submit']){
		$enabled = htmlspecialchars($_POST['enabled']);
		update_option('child_theme_logo_enabled', $enabled);

		$file_name = $_FILES['logo_image']['name'];
		$temp_file = $_FILES['logo_image']['tmp_name'];
		$file_type = $_FILES['logo_image']['type'];
		
		if($file_type=="image/gif" || $file_type=="image/jpeg" || $file_type=="image/pjpeg" || $file_type=="image/png"){
			$length=filesize($temp_file);
			$fd = fopen($temp_file,'rb');
			$file_content=fread($fd, $length);
			fclose($fd);
			
			$wud = wp_upload_dir();
			
			if (file_exists($wud[path].'/'.strtolower($file_name))){
				unlink ($wud[path].'/'.strtolower($file_name));
			}
			
			$upload = wp_upload_bits( $file_name, '', $file_content);
		//	echo $upload['error'];

			$child_theme_image = $wud[url].'/'.strtolower($file_name);
			update_option('child_theme_image', $child_theme_image);
		}
		
		?>
			<div class="updated"><p>Your new options have been successfully saved.</p></div>
		<?php

	}
	
	if($enabled) $checked='checked="checked"';

	?>
		<div class="wrap">
			<div id="icon-themes" class="icon32"></div>
			<h2>Child Theme Options</h2>
			<form name="theform" method="post" enctype="multipart/form-data" action="<?php echo str_replace( '%7E', '~', $_SERVER['REQUEST_URI']);?>">
				<table class="form-table">
					<tr>
						<td width="200">Use logo image instead of blog title and description:</td>
						<td><input type="checkbox" name="enabled" value="1" <?php echo $checked; ?>/></td>
					</tr>
					<tr>
						<td>Current image:</td>
						<td><img src="<?php echo $child_theme_image; ?>" /></td>
					</tr>
					<tr>
						<td>Logo image to use (gif/jpeg/png):</td>
						<td><input type="file" name="logo_image"><br />(you must have writing permissions for your uploads directory)</td>
					</tr>
				</table>
				<input type="hidden" name="options-submit" value="1" />
				<p class="submit"><input type="submit" name="submit" value="Save Options" /></p>
			</form>
		</div>
	<?php
}

// ---------- "Child Theme Options" menu ENDS HERE

// ---------- Adding the logo image to the header STARTS HERE

if(get_option('child_theme_logo_enabled') && !isset($pods->data['headerlogo'])){
	function remove_thematic_blogtitle() {
	 remove_action('thematic_header','thematic_blogtitle',3);
	}
	add_action('init','remove_thematic_blogtitle');

	function remove_thematic_blogdescription() {
	 remove_action('thematic_header','thematic_blogdescription',5);
	}
	add_action('init','remove_thematic_blogdescription');

	function thematic_logo_image() {
		echo '<div id="logo-image"><a href="'.get_option('home').'"><img src="'.get_option('child_theme_image').'" /></a></div>';
	}
	add_action('thematic_header','thematic_logo_image',4);
}
// ---------- Adding the logo image to the header ENDS HERE
function childtheme_theme_link($themelink) {
    return $themelink . ' &amp; <a class="child-theme-link" href="http://cozmoslabs.com" title="Street Theme" rel="designer">Street Child Theme</a>';
}
add_filter('thematic_theme_link', 'childtheme_theme_link');

function getBitlyUrl($url) {
$bitlylogin = 'kunal17';
$bitlyapikey= 'R_a723c15700f18b2b612494500eab6caf';
$bitlyurl = file_get_contents("http://api.bit.ly/shorten?version=2.0.1&longUrl=".$url."&login=".$bitlylogin."&apiKey=".$bitlyapikey);
$bitlycontent = json_decode($bitlyurl,true);
$bitlyerror = $bitlycontent["errorCode"];
if ($bitlyerror == 0) {
$bitlyurl = $bitlycontent["results"][$url]["shortUrl"];
}
else $bitlyurl = "error";
return $bitlyurl;
}

/* make a URL small */
/* usage */
//$short = make_bitly_url('http://davidwalsh.name','davidwalshblog','R_96acc320c5c423e4f5192e006ff24980','json');
//echo 'The short URL is:  '.$short;
// returns:  http://bit.ly/11Owun
function make_bitly_url($url,$login = 'kunal17',$appkey = 'R_a723c15700f18b2b612494500eab6caf',$format = 'json',$version = '2.0.1')
{
  //create the URL
	$bitly = 'http://api.bit.ly/shorten?version='.$version.'&longUrl='.urlencode($url).'&login='.$login.'&apiKey='.$appkey.'&format='.$format;
  //get the url
	//could also use cURL here
	$response = file_get_contents($bitly);
	
	//parse depending on desired format
	if(strtolower($format) == 'json')
	{
		$json = @json_decode($response,true);
		return $json['results'][$url]['shortUrl'];
	}
	else //xml
	{
		$xml = simplexml_load_string($response);
		return 'http://bit.ly/'.$xml->results->nodeKeyVal->hash;
	}
}

/* make a URL small using google url shortner, account with enthrallmedia@gmail.com */
function make_goog_url($url)
{
  $longURLData = array('longUrl' => $url);
 
  $curl = curl_init();
  curl_setopt($curl, CURLOPT_POST, 1);
  curl_setopt($curl, CURLOPT_URL, 'https://www.googleapis.com/urlshortener/v1/url?key=AIzaSyAg_Lv8VKWuDlfEbjuu0235TfyL0cjwQHk');
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
  curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($longURLData));
  $jsonResult = curl_exec($curl);
  curl_close($curl);
 
  $resultArray = json_decode($jsonResult, true);
  
  return $resultArray['id'];
}
/* make a URL small using google url shortner, account with enthrallmedia@gmail.com */

/* Returns Time Remaning in Simple English */
function time_till_expires($value){
date_default_timezone_set('Asia/Kolkata');
$enddate = date("U", strtotime($value));
$today = time();
    
// array of time period chunks
$chunks = array(
    (60 * 60 * 24 * 365),
    (60 * 60 * 24 * 30),
    (60 * 60 * 24 * 7),
    (60 * 60 * 24),
    (60 * 60),
    (60),
    (1)
);

$till = $enddate - $today;

for ($i = 0, $j = count($chunks); $i < $j; $i++) {
    $seconds = $chunks[$i];

    if (0 != $count = floor($till / $seconds))
        break;
}

$trans = array(
    _n('%d year', '%d years', $count),
    _n('%d month', '%d months', $count),
    _n('%d week', '%d weeks', $count),
    _n('%d day', '%d days', $count),
    _n('%d hour', '%d hours', $count),
    _n('%d minute', '%d minutes', $count),
    _n('%d second', '%d seconds', $count)
);

if ('0000-00-00 00:00:00' == $value) {
    $result = 'No Expiry';
}
elseif ($today >= $enddate) {
    $result = 'This offer has expired';
}
else {
    $output = sprintf($trans[$i], $count);
    $result = 'This offer expires in '.$output;
}

return $result;
}
/* Returns Time Remaning in Simple English */

//set users through facebook connect role to consumer
function set_wp_custom_fbconnect_role( $wp_userdata, $fb_userdata )
{
    $wp_userdata['role']   = 'consumer';
    $wp_userdata['user_login'] = strtolower($wp_userdata['first_name']).strtolower($wp_userdata['last_name']);
    /*
    echo "<pre>";
    print_r($fb_userdata);
    print_r($wp_userdata);
    exit();
    */
    return $wp_userdata;
}
add_filter( 'wpfb_insert_user', 'set_wp_custom_fbconnect_role', 10, 2 );

function my_widgets_init() {
	if ( !function_exists('register_sidebars') )
		return;
	  // Register Widgetized areas.
			   // Area 1
            register_sidebar(array(
       	'name' => 'Above Footer Aside 1',
       	'id' => 'above-footer-aside-1',
       	'before_widget' => '<li id="%1$s" class="widgetcontainer %2$s">',
       	'after_widget' => '</li>',
		    'before_title' => "<h3 class=\"widgettitle\">",
		    'after_title' => "</h3>\n",
    ));
				// Area 2
            register_sidebar(array(
       	'name' => 'Above Footer Aside 2',
       	'id' => 'above-footer-aside-2',
       	'before_widget' => '<li id="%1$s" class="widgetcontainer %2$s">',
       	'after_widget' => '</li>',
		    'before_title' => "<h3 class=\"widgettitle\">",
		    'after_title' => "</h3>\n",
    ));
			  // Area 3
            register_sidebar(array(
       	'name' => 'Above Footer Aside 3',
       	'id' => 'above-footer-aside-3',
       	'before_widget' => '<li id="%1$s" class="widgetcontainer %2$s">',
       	'after_widget' => '</li>',
		    'before_title' => "<h3 class=\"widgettitle\">",
		    'after_title' => "</h3>\n",
    ));
}
add_action( 'init', 'my_widgets_init' );

/* Buzzr Custom Widget Added for featured beside Sidebar */
function buzzr_widgets_init() {
	if ( !function_exists('register_sidebars') )
		return;
        register_sidebar(array(
       	'name' => 'Featured Besides Slider',
       	'id' => 'featured-besides-slider',
       	'before_widget' => '<li id="%1$s" class="widgetcontainer %2$s">',
       	'after_widget' => '</li>',
		    'before_title' => "<h3 class=\"widgettitle\">",
		    'after_title' => "</h3>\n",
    ));
}
add_action( 'init', 'buzzr_widgets_init' );
/* Buzzr Custom Widget Added for featured beside Sidebar */


// Creates the Above footer Widgets Action Hook
function above_footer_widgets() {
    do_action('above_footer_widgets');
} // end thematic_abovefooter

// Creates the above footer widgets container
function above_footer_widgets_container() {
      // adds the container div to the widgets
if ( function_exists('dynamic_sidebar') && is_sidebar_active('above-footer-aside-1') OR is_sidebar_active('above-footer-aside-2') OR is_sidebar_active('above-footer-aside-3') ) {
    //opens the container
    echo '<div id="thematic-above-footer">' . "\n" . '<div id="thematic-above-footer-widgets">' . "\n";
    // calls the widgets
    above_footer_widgets ();
    //closes the container
    echo '</div><!-- thematic-above-footer-widgets -->' . "\n" . '</div><!-- thematic-above-footer -->' . "\n"  ;
}
}
add_action('thematic_abovefooter', 'above_footer_widgets_container');

// adds  widget areas to the thematic_abovefooter hook
function insert_above_footer_widgets() {
      // Area 1
if ( function_exists('dynamic_sidebar') && is_sidebar_active('above-footer-aside-1') ) {
    echo '<div id="above-footer-aside-1" class="aside footeraside">'. "\n" . '<ul class="xoxo">' . "\n";
    dynamic_sidebar('above-footer-aside-1');
    echo "\n" . '</ul>' . "\n" . '</div><!-- #above-footer-aside-1 .aside -->'. "\n";
}
      // Area 2
if ( function_exists('dynamic_sidebar') && is_sidebar_active('above-footer-aside-2') ) {
    echo '<div id="above-footer-aside-2" class="aside footeraside">'. "\n" . '<ul class="xoxo">' . "\n";
    dynamic_sidebar('above-footer-aside-2');
    echo "\n" . '</ul>' . "\n" . '</div><!-- #above-footer-aside-2 .aside -->'. "\n";
}
      // Area 3
if ( function_exists('dynamic_sidebar') && is_sidebar_active('above-footer-aside-3') ) {
    echo '<div id="above-footer-aside-3" class="aside footeraside">'. "\n" . '<ul class="xoxo">' . "\n";
    dynamic_sidebar('above-footer-aside-3');
    echo "\n" . '</ul>' . "\n" . '</div><!-- #above-footer-aside-3 .aside -->'. "\n";
}
}
add_action('above_footer_widgets', 'insert_above_footer_widgets');

function admin_select_nav()
{
  if (is_user_logged_in()){
  	global $current_user;
  	$user_roles = $current_user->roles;
  	$user_role = array_shift($user_roles);
  	if ($user_role == 'moderator' || $user_role == 'administrator')
  	{
  	 $o.= '<div style="float:left; margin-left: 35%;"><select name="exampleselect" onchange="window.open(this.value);">';
  	   $o.= '<option value="#">-- Select Page --</option>';
       $o.= '<option value="'.get_bloginfo('url').'/admin/dashboard">Admin Dashboard</option>';
  	   $o.= '<option value="'.get_bloginfo('url').'/admin/comments">Comments</option>';
  	   $o.= '<option value="'.get_bloginfo('url').'/admin/search">Search Queries</option>';
  	   $o.= '<option value="'.get_bloginfo('url').'/admin/catdaily">Daily Deals Categories</option>';
  	   $o.= '<option value="'.get_bloginfo('url').'/admin/newdeal">New Deal</option>';
  	   $o.= '<option value="'.get_bloginfo('url').'/admin/newdaily">New Daily</option>';
  	   $o.= '<option value="'.get_bloginfo('url').'/admin/newcoupon">New Coupon</option>';
  	   $o.= '<option value="'.get_bloginfo('url').'/admin/newbrand">New Brand</option>';
  	   $o.= '<option value="'.get_bloginfo('url').'/wordpress/buzzr_stats.php">Buzzr Stats</option>';
  	 $o.= '</select></div>';
  	 echo $o;
  	}
	}
}
add_action('thematic_header','admin_select_nav',4);

function total_offers()
{
  $offers = new Pod('deal');
  $offers->page = 1;
  $offers->search = false;
  $where = "t.camp_end > ".fix_date();
  $offers->findRecords('id DESC', -1, $where);
  $total_offers = $offers->getTotalRows()." Active Offers";
  
  
  $brand = new Pod('brand');
  $brand->page = 1;
  $brand->search = false;
  $where = "campaigns.camp_end > ".fix_date();
  $brand->findRecords('id DESC', -1, $where);
  $total_brands = $brand->getTotalRows()." Stores";
  
  $op.= '<div class="total_offers">';
  $op.= $total_offers.' from '.$total_brands;
  $op.= '</div>';
  echo $op;
}
add_action('thematic_header','total_offers',4);


//add link to control panel from admin menu
function add_link_to_menu($output) {
	$output .= "<li><a title='Deals' href='http://buzzr.in/deals'>Deals</a></li>";
	$output .= "<li><a title='Coupons' href='http://buzzr.in/coupons'>Coupons</a></li>";
	$output .= "<li><a title='Local Offers' href='http://buzzr.in/localoffers'>Local Offers</a></li>";
	$output .= "<li><a title='Daily Deals' href='http://buzzr.in/dailydeals'>Daily Deals</a></li>";
	$output .= "<li><a title='Stores' href='http://buzzr.in/stores'>Stores</a></li>";
	$output .= "<li><a title='Blog' href='http://buzzr.in/blog'>Blog</a></li>";
  $output .= "<li><a href='http://buzzr.in/get-points' title='Know how to score points!'>Get Points!</a></li>";
  $output .= "<li><a title='Share Local Offers' href='http://buzzr.in/add-offer'>Share Local Offers</a></li>";
  if (is_user_logged_in()){
	global $current_user;
	$user_roles = $current_user->roles;
	$user_role = array_shift($user_roles);
	if ($user_role != 'consumer' && $user_role != 'moderator' && $user_role != 'administrator' && $user_role != 'author')
	{
		$output .= "<li><a href='http://buzzr.in/advertisers/dashboard' title='Your Dashboard'>Dashboard</a></li>\n";
	}
	
	/*
  elseif($user_role == 'moderator')
	{
		//$output .= "<li><a href='http://buzzr.in/advertisers/dashboard' title='Your Dashboard'>Dashboard</a></li>\n";		
		$output .= "<li><a href='http://buzzr.in/admin/dashboard' title='Your Dashboard'>Admin Dashboard</a></li>\n";
		$output .= "<li><a href='http://buzzr.in/admin/newdeal' title='Add New Deal'>New Deal</a></li>\n";
		$output .= "<li><a href='http://buzzr.in/admin/newdaily' title='Add New Daily Deal'>New Daily</a></li>\n";
		$output .= "<li><a href='http://buzzr.in/admin/newcoupon' title='Add New Coupon'>New Coupon</a></li>\n";
		$output .= "<li><a href='http://buzzr.in/admin/newbrand' title='Add New Brand'>New Brand</a></li>\n";
		$output .= "<li><a href='http://buzzr.in/admin/comments' title='Manage Comments'>Comments</a></li>\n";
		$output .= "<li><a href='http://buzzr.in/admin/search' title='Manage Comments'>Search Queries</a></li>\n";
	}
	elseif($user_role == 'administrator')
	{
		//$output .= "<li><a href='http://buzzr.in/advertisers/dashboard' title='Your Dashboard'>Dashboard</a></li>\n";		
		$output .= "<li><a href='http://buzzr.in/admin/dashboard' title='Your Dashboard'>Admin Dashboard</a></li>\n";
		$output .= "<li><a href='http://buzzr.in/admin/comments' title='Manage Comments'>Comments</a></li>\n";
		$output .= "<li><a href='http://buzzr.in/admin/search' title='Manage Comments'>Search Queries</a></li>\n";
	}
	*/
}
        return $output;
}
add_filter('wp_list_pages', 'add_link_to_menu');

/* BOF Custom Buzzr
Function Filters the Content & removes the links from the images in the content
*/ 
function remove_links($content){
    $postOutput = preg_replace('/><a [^><]+><img[^>]/','/><img/', $content);
    return $postOutput;
}
 
// Add this function to the WordPress hook
add_filter('the_content', 'remove_links');
add_filter('the_excerpt', 'remove_links');
/* EOF Custom Buzzr */ 

/* BOF Custom Buzzr
Function Uses Data Dumped by the custom file placed inside wp-content/plugins/google-xml-sitemap/buzzr_sitemap.php
from file located as /home/kunal17/public_html/buzzr/buzzr_sitemap.xml
attaches the data after using unserialize to the Google XML sitemap Generator object, which is called everytime the the sitemap is regenerated, thus makin a combined XML file of WP + PODS :)
*/ 
function pods_pages() {
$file = '/var/www/buzzr/buzzr_sitemap.xml';
$fileHandle = fopen($file, "rb");
$fileContents = fread($fileHandle, filesize($file));
fclose($fileHandle);
$links = unserialize($fileContents);

$count = count($links['url']);
$generatorObject = &GoogleSitemapGenerator::GetInstance(); //Please note the "&" sign for PHP4!
if($generatorObject != null){
	for($i=0; $i<$count; $i++)
	{
	    $generatorObject->AddUrl($links['url'][$i],$links['last_mod'][$i],$links['change_freq'][$i],$links['priority'][$i]);
	}
}

}
add_action("sm_buildmap","pods_pages");

/* EOF Custom Buzzr */

/* BOF Custom Buzzr */
/* Function basically detects if user is logged in n assigns points for login per day
detects if the user has a points pod too, if not creates one n modifies the necessary 
user pod details too */

function logged_in_points()
{
    if(is_user_logged_in())
    {
      global $current_user;
      get_currentuserinfo();
      $wp_id = $current_user->ID;
      $user_roles = $current_user->roles;
      $user_role = array_shift($user_roles);

      if ($user_role == 'administrator' || $user_role == 'consumer')
      {
      date_default_timezone_set('Asia/Kolkata');
      $users = new Pod('users');
      $users->page = 1;
      $users->search = false;
      $users->findRecords('id DESC', "1", "wp_user.id ='$wp_id'");
      while ($users->fetchRecord())
      {
          $users_id = $users->get_field('id');
  	      $users_name = $users->get_field('name');
  	      $login_day = $users->get_field('login_day');
      }
  
      $points = new Pod('points');
      $points->page = 1;
      $points->search = false;
      $points->findRecords('id DESC', "1", "user.id ='$users_id'");
      
      $pod_item_exits = $points->getTotalRows();
  
      if($pod_item_exits == 1)
      {
  	    while ($points->fetchRecord())
  	    {
      		$id = $points->get_field('id');
      		$login_points = $points->get_field('login');
  	    }
  
        if(empty($login_day))
        {
          $api = new PodAPI();
    	    $columns_points['login'] = ($login_points + 50);
    	    $params = array('datatype' => 'points','tbl_row_id' => $id, 'columns' => $columns_points);
    	    $api->save_pod_item($params);
    	    $login_day_mod = date('Y-m-d');
        }
        elseif(strtotime($login_day) < strtotime(date('Y-m-d')))
        {
          $api = new PodAPI();
    	    $columns_points['login'] = ($login_points + 50);
    	    $params = array('datatype' => 'points','tbl_row_id' => $id, 'columns' => $columns_points);
    	    $api->save_pod_item($params);
    	    $login_day_mod = date('Y-m-d');
        }
        
        $api = new PodAPI();
  	    if(!empty($login_day_mod))
  	    {
          $columns_consumer['login_day'] = $login_day_mod; 
        }
        $columns_consumer['last_login'] = date('Y-m-d H:i:s');
  	    $params = array('datatype' => 'users','tbl_row_id' => $users_id, 'columns' => $columns_consumer);
  	    $api->save_pod_item($params);
      }
      else
      {
     	 $api = new PodAPI();
  	   $columns_points['name'] = $users_name;
  	   $columns_points['slug'] = $users_name;
  	   $columns_points['registration'] = '1000';
  	   $columns_points['login'] = '50';
  	   $columns_points['comments'] = '0';
  	   $columns_points['deals'] = '0';
  	   $columns_points['like_fb'] = '0';
  	   $columns_points['vote'] = '0';
  	   $columns_points['feedback'] = '0';
  	   $columns_points['referral'] = '0';
  	   $columns_points['user'] = $users_id;
  	   $params = array('datatype' => 'points','columns' => $columns_points);
  	   $api->save_pod_item($params);
  	   
  	   $columns_consumer['login_day'] = date('Y-m-d');
  	   $columns_consumer['last_login'] = date('Y-m-d H:i:s');
  	   $params = array('datatype' => 'users','tbl_row_id' => $users_id, 'columns' => $columns_consumer);
  	   $api->save_pod_item($params); 
      }
    }
  }
}
add_action('wp_head', 'logged_in_points');


/* BOF Custom Buzzr */
/* Function hooks into the FB-Autoconnect login hook to check if user 
loggin in has a pod item, if not creates one for the user */
function users_new_pod_item($args)
{
  $wp_id = $args['WP_ID'];
  $users = new Pod('users');
  $users->page = 1;
  $users->search = false;
  $users->findRecords('id DESC', -1, "wp_user.id ='$wp_id'");
  $total_rows = $users->getTotalRows();
  if($total_rows == '0')
  {
    date_default_timezone_set('Asia/Kolkata');
    $api = new PodAPI();
    $user_firstname = get_user_meta($wp_id, 'first_name', 'true');
    $user_lastname = get_user_meta($wp_id, 'last_name', 'true');
    $columns_user['name'] = $user_firstname.' '.$user_lastname;
    $columns_user['slug'] = $columns['name'];
    $columns_user['wp_user'] =  $wp_id;
    $columns_user['login_day'] = date('Y-m-d');
	  $columns_user['last_login'] = date('Y-m-d H:i:s');
    $params = array('datatype' => 'users','columns' => $columns_user);
    $api->save_pod_item($params);
    
    
    $users = new Pod('users');
    $users->page = 1;
    $users->search = false;
    $users->findRecords('id DESC', "1", "wp_user.id ='$wp_id'");
    while ($users->fetchRecord())
    {
        $users_id = $users->get_field('id');
    }
    
    $columns_points['name'] = $columns_user['name'];
    $columns_points['slug'] = $columns['name'];
    $columns_points['registration'] = '1000';
    $columns_points['login'] = '0';
    $columns_points['comments'] = '0';
    $columns_points['deals'] = '0';
    $columns_points['like_fb'] = '0';
    $columns_points['vote'] = '0';
    $columns_points['feedback'] = '0';
    $columns_points['referral'] = '0';
    $columns_points['user'] = $users_id;
    $params = array('datatype' => 'points','columns' => $columns_points);
    $api->save_pod_item($params);
  }
  elseif($total_rows == '1')
  {
    date_default_timezone_set('Asia/Kolkata');
    $users = new Pod('users');
    $users->page = 1;
    $users->search = false;
    $users->findRecords('id DESC', "1", "wp_user.id ='$wp_id'");
    while ($users->fetchRecord())
    {
        $users_id = $users->get_field('id');
	      $users_name = $users->get_field('name');
	      $login_day = $users->get_field('login_day');
    }

    $points = new Pod('points');
    $points->page = 1;
    $points->search = false;
    $points->findRecords('id DESC', "1", "user.id ='$users_id'");
    $pod_item_exits = $points->getTotalRows();

    if($pod_item_exits == 1)
    {
	    while ($points->fetchRecord())
	    {
    		$id = $points->get_field('id');
    		$login_points = $points->get_field('login');
	    }

      if(empty($login_day))
      {
        $api = new PodAPI();
  	    $columns_points['login'] = ($login_points + 50);
  	    $params = array('datatype' => 'points','tbl_row_id' => $id, 'columns' => $columns_points);
  	    $api->save_pod_item($params);
  	    $login_day_mod = date('Y-m-d');
      }
      elseif(strtotime($login_day) < strtotime(date('Y-m-d')))
      {
        $api = new PodAPI();
  	    $columns_points['login'] = ($login_points + 50);
  	    $params = array('datatype' => 'points','tbl_row_id' => $id, 'columns' => $columns_points);
  	    $api->save_pod_item($params);
  	    $login_day_mod = date('Y-m-d');
      }
      
      $api = new PodAPI();
	    if(!empty($login_day_mod))
	    {
        $columns_consumer['login_day'] = $login_day_mod; 
      }
      $columns_consumer['last_login'] = date('Y-m-d H:i:s');
	    $params = array('datatype' => 'users','tbl_row_id' => $users_id, 'columns' => $columns_consumer);
	    $api->save_pod_item($params); 
    }
    else
    {
   	 $api = new PodAPI();
	   $columns_points['name'] = $users_name;
	   $columns_points['slug'] = $users_name;
	   $columns_points['registration'] = '1000';
	   $columns_points['login'] = '50';
	   $columns_points['comments'] = '0';
	   $columns_points['deals'] = '0';
	   $columns_points['like_fb'] = '0';
	   $columns_points['vote'] = '0';
	   $columns_points['feedback'] = '0';
	   $columns_points['referral'] = '0';
	   $columns_points['user'] = $users_id;
	   $params = array('datatype' => 'points','columns' => $columns_points);
	   $api->save_pod_item($params);
	   
	   $columns_consumer['login_day'] = date('Y-m-d');
	   $columns_consumer['last_login'] = date('Y-m-d H:i:s');
	   $params = array('datatype' => 'users','tbl_row_id' => $users_id, 'columns' => $columns_consumer);
	   $api->save_pod_item($params); 
    }
  }
}
add_action('wpfb_login', 'users_new_pod_item');
/* BOF Custom Buzzr */

/* BOF Custom Buzzr */
/* Function hooks into the WP-Register's Hook to check if user 
loggin in has a pod item, if not creates one for the user */

function users_new_pod_item_wp($user_id)
{
  $daily_cat = new Pod('category');
  $daily_cat->page = 1;
  $daily_cat->search = false; 
  $daily_cat->findRecords('id ASC', -1, "is_local =1 OR is_daily=1");
  while($daily_cat->fetchRecord())
  {
    $cat_prefs[] = $daily_cat->get_field('id');
  }
  $cat_prefs = implode(',',$cat_prefs);
  
  $users = new Pod('users');
  $users->page = 1;
  $users->search = false; 
  $users->findRecords('id DESC', "", "wp_user.id ='$user_id'");
  $total_rows = $users->getTotalRows();
  $api = new PodAPI();
  if($total_rows == '0')
  {
    date_default_timezone_set('Asia/Kolkata');
    //$user_data = get_userdata($user_id);
    //$first = $user_data->first_name;
    //$last = $user_data->last_name;
    $first = get_user_meta($user_id,'first_name',true);
    $last = get_user_meta($user_id,'last_name',true);
    
    $daily = get_user_meta($user_id,'get_daily_newsletter',true);
    if($daily == 'Daily Newsletter'){
      $columns_user['daily_newsletter'] = 1;
    }
    
    $daily_city_name = get_user_meta($user_id,'city',true);
    
    if(!empty($daily_city_name)){
      $daily_city = new Pod('city');
      $daily_city->page = 1;
      $daily_city->search = false; 
      $daily_city->findRecords('id ASC', -1, "t.name ='$daily_city_name'");
      while($daily_city->fetchRecord())
      {
        $daily_city_id = $daily_city->get_field('id');
      }
      $columns_user['city'] = $daily_city_id;
    }
     
    $columns_user['name'] = $first.' '.$last; 
    $columns_user['wp_user'] =  $user_id;
    $columns_user['slug'] =  "";
    $columns_user['login_day'] = date('Y-m-d');
	  $columns_user['last_login'] = date('Y-m-d H:i:s');
	  $columns_user['categories'] = $cat_prefs;
	  session_start();
    if(isset($_SESSION['daily_signup']) && $_SESSION['daily_signup'] == 1)
    {
      $columns_user['daily_newsletter'] = 1;
      $columns_user['city'] = $_SESSION['daily_city'];
      unset($_SESSION['daily_signup']);
      unset($_SESSION['daily_city']);
      session_destroy();
    }
    $params = array('datatype' => 'users','columns' => $columns_user);
    $api->save_pod_item($params);
    
    $users = new Pod('users');
    $users->page = 1;
    $users->search = false; 
    $users->findRecords('id DESC', 1, "wp_user.id ='$user_id'");
    while($users->fetchRecord())
    {
      $user_pod_id = $users->get_field('id');
    }
    
    $columns_points['name'] = $columns_user['name'];
    $columns_points['slug'] = "";
    $columns_points['registration'] = '1000';
    $columns_points['login'] = '0';
    $columns_points['comments'] = '0';
    $columns_points['deals'] = '0';
    $columns_points['like_fb'] = '0';
    $columns_points['vote'] = '0';
    $columns_points['feedback'] = '0';
    $columns_points['referral'] = '0';
    $columns_points['user'] = $user_pod_id; 
    $params_points = array('datatype' => 'points','columns' => $columns_points);
    $api->save_pod_item($params_points);
  } 
}
add_action('user_register', 'users_new_pod_item_wp');


function users_pod_name()
{
if(is_user_logged_in())
{
global $current_user;
get_currentuserinfo();
$wp_id = $current_user->ID;
$user_data = get_userdata($wp_id);
$first = ucwords($user_data->first_name);
$last = ucwords($user_data->last_name);

$users = new Pod('users');
$users->page = 1;
$users->search = false; 
$users->findRecords('id DESC', 1, "wp_user.id ='$wp_id'");
while($users->fetchRecord())
{
$user_slug = $users->get_field('slug');
$user_pod_id = $users->get_field('id');
}

$points = new Pod('points');
$points->page = 1;
$points->search = false; 
$points->findRecords('id DESC', 1, "user.id ='$user_pod_id'");
while($points->fetchRecord())
{
$points_pod_id = $points->get_field('id');
$points_login = $points->get_field('login');
}

if(strlen($user_slug) <= 0 || $user_slug < 0 || $user_slug == '-1')
{
  $api = new PodAPI();
  $columns_user['name'] = $first.' '.$last;
  $columns_user['slug'] = sanitize_title($columns_user['name']);
  $params = array('datatype' => 'users','tbl_row_id' => $user_pod_id ,'columns' => $columns_user);
  $api->save_pod_item($params);
  
  $columns_points['name'] = $columns_user['name'];
  $columns_points['slug'] = sanitize_title($columns_user['name']);
  $params_points = array('datatype' => 'points','tbl_row_id' => $points_pod_id ,'columns' => $columns_points);
  $api->save_pod_item($params_points);  
}

if(isset($_COOKIE['buzzr_refer']))
{
  $referer_slug = $_COOKIE['buzzr_refer'];
  $pastdate = mktime(0,0,0,1,1,1970);
  setcookie("buzzr_refer","",$pastdate);
  $referer = new Pod('users',$referer_slug);
  $referer_id = $referer->get_field('id');
  $referer_ref_points = $referer->get_field('points.referral');
  $referer_ref_points_id = $referer->get_field('points.id');
  $columns_user['referred_by_user'] = $referer_id;
  
  $api = new PodAPI();
  $params = array('datatype' => 'users','tbl_row_id'=>$user_pod_id,'columns' => $columns_user);
  $api->save_pod_item($params);
}
    
    
if(!empty($referer_id))
{
    $api = new PodAPI();
    $columns_referer['users_referred'] = $user_pod_id;//new user's pod item id
    $params_ref = array('datatype' => 'users','tbl_row_id'=>$referer_id,'columns' => $columns_referer);
    $api->save_pod_item($params_ref);
    
    $columns_ref_points['referral'] = ($referer_ref_points + 300);
    $params_ref_points = array('datatype' => 'points','tbl_row_id'=>$referer_ref_points_id,'columns' => $columns_ref_points);
    $api->save_pod_item($params_ref_points);
} 

}
}
add_action('wp_head', 'users_pod_name');
/* EOF Custom Buzzr */

/* BOF Buzzr SuperCache Change for Pods CMS */
/* Hooks into supercache to delete cache based on pod save item events */
    add_action('pods_post_save_pod_item','wp_cache_clear_cache');
    add_action('pods_post_drop_pod_item','wp_cache_clear_cache');
/* EOF Buzzr SuperCache for Pods CMS */

/* BOF Buzzr Call Contact Form 7 JS & Styles only on specific Pages */
function deregister_cf7_js()
{
  if(!is_page(array('contact-us','feedback','advertisers','write-for-us')) && !is_pod_page('advertisers/dashboard'))
  {
  	wp_deregister_script('contact-form-7');
  }
}
add_action('wp_print_scripts', 'deregister_cf7_js', 100);

function deregister_cf7_css()
{
  if(!is_page(array('contact-us','feedback','advertisers','write-for-us')) && !is_pod_page('advertisers/dashboard'))
  {
  	wp_deregister_style('contact-form-7');
  }
}
add_action('wp_print_styles', 'deregister_cf7_css', 100);
/* BOF Buzzr Call Contact Form 7 JS & Styles only on specific Pages */


/* Buzzr Encyption Functions Key = 1b2u3z4z5r6 */
function decrypt($string, $key)
{
    $string = str_replace('WPT', '/', $string);
    $string = str_replace('W1PT', '+', $string);
    $string = base64_decode($string);
    /* Open the cipher */
    $td = mcrypt_module_open(MCRYPT_RIJNDAEL_256, '', MCRYPT_MODE_CFB, '');
    /* Get IV  and keysize length */
    $iv_size = mcrypt_enc_get_iv_size($td);
    $iv = substr($string,0,$iv_size);
    $string = substr($string,$iv_size);
    $ks = mcrypt_enc_get_key_size($td);
    /* Create key */
    $key = substr(md5($key), 0, $ks);
    /* Initialize encryption module for decryption */
    mcrypt_generic_init($td, $key, $iv);
    /* Decrypt encrypted string */
    $decrypted = mdecrypt_generic($td, $string);
    /* Terminate decryption handle and close module */
    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);
    return $decrypted;
  }

function encrypt($string, $key)
{
    /* Open the cipher */
    $td = mcrypt_module_open(MCRYPT_RIJNDAEL_256, '', MCRYPT_MODE_CFB, '');
    /* Create the IV and determine the keysize length, use MCRYPT_RAND on Windows instead  and MCRYPT_DEV_RANDOM on Linux*/
    $iv_size = mcrypt_enc_get_iv_size($td);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    $ks = mcrypt_enc_get_key_size($td);
    /* Create key */
    $key = substr(md5($key), 0, $ks);
    /* Intialize encryption */
    mcrypt_generic_init($td, $key, $iv);
    /* Encrypt data */
    $encrypted = mcrypt_generic($td, $string);
    /* Terminate encryption handle and close module */
    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);
    $encrypted = $iv.$encrypted;
    $return = base64_encode($encrypted);
    $return = str_replace('/', 'WPT', $return);
    $return = str_replace('+', 'W1PT', $return);
    return $return;
  }
/* Buzzr Encyption Functions */


/* Buzzr Facebook Like iFrame */
function buzzr_fb_like($like_url,$faces = '')
{
   if(!empty($faces))
   {
      echo '<iframe src="http://www.facebook.com/plugins/like.php?href=http://buzzr.in'.$like_url.'&amp;show_faces=true&amp;width=450&amp;action=like&amp;font=segoe+ui&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:250px; height:100px;" allowTransparency="true"></iframe>';
   }
   else
   {
      echo '<iframe src="http://www.facebook.com/plugins/like.php?href=http://buzzr.in'.$like_url.'&amp;layout=button_count&amp;width=450&amp;action=like&amp;font=segoe+ui&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:80px; height:20px;" allowTransparency="true"></iframe>';
   } 
}
/* Buzzr Facebook Like iFrame */

/* Buzzr FiX End Date Check in SQL POD Queries */
function fix_date()
{
 $string = "DATE_ADD(NOW(), INTERVAL '05:30' HOUR_MINUTE)";
 return $string;
}
/* Buzzr FiX End Date Check in SQL POD Queries */

/* Buzzr Send HTML Mail Function */
function send_html_mail($to, $subject, $msg, $from, $plaintext = '')
{
    if(!is_array($to)) $to = array($to);

    foreach($to as $address)
    {
        $boundary = uniqid(rand(), true);

        $headers  = "From: $from\n";
        $headers .= "MIME-Version: 1.0\n";
        $headers .= "Content-Type: multipart/alternative; boundary = $boundary\n";
        $headers .= "This is a MIME encoded message.\n\n";
        $headers .= "--$boundary\n" .
                    "Content-Type: text/plain; charset=ISO-8859-1\n" .
                    "Content-Transfer-Encoding: base64\n\n";
        $headers .= chunk_split(base64_encode($plaintext));
        $headers .= "--$boundary\n" .
                    "Content-Type: text/html; charset=ISO-8859-1\n" .
                    "Content-Transfer-Encoding: base64\n\n";
        $headers .= chunk_split(base64_encode($msg));
        $headers .= "--$boundary--\n" .

        mail($address, $subject, '', $headers);
    }
}
/* Buzzr Send HTML Mail Function */

/* Buzzr Fb-AutoConnect Login Button */
/* Function is responsible for outputing the login/logout button on the header
plus outputs the users profile page link along with their points too*/
function login_button()
{ 
if (!is_user_logged_in()){
echo '<div class="fblogin nlogin">';
echo '<div id="notice_content_1">';
echo '<span style="font-size: 12px; font-weight: bold;">Register/Login to Earn Points!</span>';
jfb_output_facebook_btn();
jfb_output_facebook_init();
jfb_output_facebook_callback();
echo '<div style="font-size:15px;"><a rel="nofollow" href="/wordpress/wp-login.php" class="simplemodal-login">Log In</a>';
echo '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a rel="nofollow" href="/wordpress/wp-login.php?action=register">Register</a></div>';
}
else {
echo '<div class="fblogin logout">';
echo '<div id="notice_content">';
global $current_user;
get_currentuserinfo();
$user_roles = $current_user->roles;
$user_role = array_shift($user_roles);
if($user_role == 'consumer' || $user_role == 'administrator' || $user_role == 'author')
{
$wp_id = $current_user->ID;
$user = new Pod('users');
$user->page = 1;
$user->search = false;
$user->findRecords('id DESC', "1", "wp_user.id = '$wp_id'");

while($user->fetchRecord())
{
  $user_slug = $user->get_field('slug');
  $user_name = $user->get_field('name');
  $user_points_reg = $user->get_field('points.registration');
  $user_points_login = $user->get_field('points.login');
  $user_points_comments = $user->get_field('points.comments');
  $user_points_deals = $user->get_field('points.deals');
  $user_points_like_fb = $user->get_field('points.like_fb');
  $user_points_feedback = $user->get_field('points.feedback');
  $user_points_vote = $user->get_field('points.vote');
  $user_points_referral = $user->get_field('points.referral');
  $user_paid_affiliate = $user->get_field('paid_affiliate');
  if(!empty($user_paid_affiliate)){ $user_referrals = $user->get_field('users_referred'); }
}

if(empty($user_paid_affiliate)){
  $total_points = $user_points_reg + $user_points_login + $user_points_comments + $user_points_deals + $user_points_like_fb + $user_points_feedback + $user_points_vote + $user_points_referral;
  echo '<a href="'.wp_logout_url(get_bloginfo('url')).'" title="Logout"><img src="'.get_bloginfo('wpurl').'/wp-content/pfiles/images/logout.png" /></a><div class="salut_wrap"><div class="salut">Hi, <a title="Click to View Your Dashboard!" href="'.get_bloginfo('url').'/member/'.$user_slug.'">'.$current_user->user_firstname.'</a></div><div class="salut_points"><b>Points: </b>'.$total_points.'</div><a rel="nofollow" title="Help to Score More Points!" href="'.get_bloginfo('url').'/get-points/"><span class="superscr">?</span></a></div><div class="salut_image">'.get_avatar($wp_id,'50').'</div>';
}
else{
  $count_ref = count($user_referrals);
  echo '<a href="'.wp_logout_url(get_bloginfo('url')).'" title="Logout"><img src="'.get_bloginfo('wpurl').'/wp-content/pfiles/images/logout.png" /></a><div class="salut_wrap"><div class="salut">Hi, <a title="Click to View Your Dashboard!" href="'.get_bloginfo('url').'/member/'.$user_slug.'">'.$current_user->user_firstname.'</a></div><div class="salut_points"><b>Users Referred: </b>'.$count_ref.'</div></div><div class="salut_image">'.get_avatar($wp_id,'50').'</div>';
}
}
elseif ($user_role == 'brand')
{
  echo '<div class="salut_wrap"><div class="salut">Hi, '.$current_user->user_firstname.'</div><a title="Click to View Your Dashboard!" href="'.get_bloginfo('url').'/advertisers/dashboard/">Dashboard</a></div>';
}
else
{
  echo '<a href="'.wp_logout_url(get_bloginfo('url')).'" title="Logout"><img src="'.get_bloginfo('wpurl').'/wp-content/pfiles/images/logout.png" /></a><div class="salut_wrap"><div class="salut">Hi, '.$current_user->user_firstname.'</a></div></div><div class="salut_image">'.get_avatar($wp_id,'50').'</div>';
}
}
echo '</div>';
echo '</div>';
}
add_action('thematic_header','login_button',4);
/* Buzzr Fb-AutoConnect Login Button */

/* Buzzr Array Order By function, used for sorting a multidimensional array by 2 parameters,
usage as explained in example below in comment */
/* $sorted = array_orderby($user, 'total_points', SORT_DESC, 'modified', SORT_ASC); */
function array_orderby()
{
    $args = func_get_args();
    $data = array_shift($args);
    foreach ($args as $n => $field) {
        if (is_string($field)) {
            $tmp = array();
            foreach ($data as $key => $row)
                $tmp[$key] = $row[$field];
            $args[$n] = $tmp;
            }
    }
    $args[] = &$data;
    call_user_func_array('array_multisort', $args);
    return array_pop($args);
}
/* Buzzr Array Order By function */


/* Buzzr Remove SKip to Content Link add new Access Menu */
function remove_thematic_actions() {
 remove_action('thematic_header','thematic_access',9);
}
add_action('init','remove_thematic_actions');

// Create #access
// In the header div
function thematic_access1() { ?>
    	<div id="access">
            <?php wp_page_menu('sort_column=menu_order') ?>
        </div><!-- #access -->
<?php }
add_action('thematic_header','thematic_access1',9);
/* Buzzr Remove SKip to Content Link add new Access Menu */

function adwords()
{
  echo '<!-- Google Code for Registration Conversion Page -->
<script type="text/javascript">
/* <![CDATA[ */
var google_conversion_id = 996473455;
var google_conversion_language = "en";
var google_conversion_format = "3";
var google_conversion_color = "ffffff";
var google_conversion_label = "6WTECInnmwIQ7_ST2wM";
var google_conversion_value = 0;
if (0.1) {
  google_conversion_value = 0.1;
}
/* ]]> */
</script>
<script type="text/javascript" src="http://www.googleadservices.com/pagead/conversion.js">
</script>
<noscript>
<div style="display:inline;">
<img height="1" width="1" style="border-style:none;" alt="" src="http://www.googleadservices.com/pagead/conversion/996473455/?value=0.1&amp;label=6WTECInnmwIQ7_ST2wM&amp;guid=ON&amp;script=0"/>
</div>
</noscript>';
}
add_action('user_register','adwords');


/* Code to Calculate time since */
function time_since($time_to_calc)
{
  $original = date("U", strtotime($time_to_calc));
  $today = time();
      
  // array of time period chunks
  $chunks = array(
      (60 * 60 * 24 * 365),
      (60 * 60 * 24 * 30),
      (60 * 60 * 24 * 7),
      (60 * 60 * 24),
      (60 * 60),
      (60),
      (1)
  );
  
  $since = $today - $original;
  
  for ($i = 0, $j = count($chunks); $i < $j; $i++) {
      $seconds = $chunks[$i];
  
      if (0 != $count = floor($since / $seconds))
          break;
  }
  
  $trans = array(
      _n('%d year', '%d years', $count),
      _n('%d month', '%d months', $count),
      _n('%d week', '%d weeks', $count),
      _n('%d day', '%d days', $count),
      _n('%d hour', '%d hours', $count),
      _n('%d minute', '%d minutes', $count),
      _n('%d second', '%d seconds', $count)
  );
  
  if ('0000-00-00 00:00:00' == $value) {
      $time_since = 'never';
  }
  elseif ($today == $original) {
      $time_since = 'less than a second';
  }
  else {
      $time_since = sprintf($trans[$i], $count);
  }
return $time_since;
}
/* Code to Calculate time since */

function check_daily_category($deal_title)
{
$cat['c-restaurants-clubs-offers'] = array('food','restaurant','brunch','meal','drinks','eat','breakfast','coffee','cappuccino','ice','cream','cuisine','egg','pub','pubs','juice','juices','veg','non-veg','dine','buffet','pizza','pizzas','beverage','beverages','biryani','soup','chicken');
$cat['c-health-and-beauty-offers'] = array('spa','massage','relaxation','gym','fitness','tattoo','dental','haircut','nail','ayurveda','hair','beauty','therapy','care');
$cat['c-flowers-gifts-offers'] = array('flowers','customized','gift','cake');
$cat['c-entertainment-offers'] = array('movie','concert','show','performance','event');
$cat['c-services-offers'] = array('amc','maintainence','service','services','classes');
$cat['c-shopping-offers'] = array('furnishing','kurta','tunic','sale','kid','shop','voucher','vouchers','perfume');

unset($string);
$string = strtolower($deal_title);

$max = array(null, 0); // category, occurences
foreach($cat as $k => $v) {
  $replaced = str_replace($v, '##########', $string);
  preg_match_all('/##########/i', $replaced, $matches);
  if(count($matches[0]) > $max[1]) {
    $max[0] = $k;
    $max[1] = count($matches[0]);
  }
}

//echo "Category {$max[0]} has the most ({$max[1]}) matches.\n";
if(!empty($max[0]) && $max[1] > 0)
{
$cat_pod = new Pod('category');
$cat_pod->search = false;
$cat_pod->page = 1;
$cat_pod->findRecords('id DESC', -1, "t.url='$max[0]'");
unset($cat_id);
while($cat_pod->fetchRecord())
{
  $cat_id = $cat_pod->get_field('id');
}

}
//echo $cat_id;
return $cat_id;
}


/* Buzzr Remove Update Nag */
function no_update_nag() {
  remove_action( 'admin_notices', 'update_nag', 3 );
}
add_action( 'admin_init', 'no_update_nag' );
/* Buzzr Remove Update Nag */

/* Buzzr GA Cookie */
function getUtm(){
    $utm = array();
    if(!empty($_COOKIE['__utmz'])){
        $pattern = "/(utmcsr=([^\|]*)[\|]?)|(utmccn=([^\|]*)[\|]?)|(utmcmd=([^\|]*)[\|]?)|(utmctr=([^\|]*)[\|]?)|(utmcct=([^\|]*)[\|]?)/i";
        preg_match_all($pattern, $_COOKIE['__utmz'], $matches);
        if(!empty($matches[0])){
            foreach($matches[0] as $match){
                $pair = null;
                $match = trim($match, "|");
                list($k, $v) = explode("=", $match);
                $utm[$k] = $v;
           }
        }
    }
    return $utm;
}
/* Buzzr GA Cookie */


/**
 * xml2array() will convert the given XML text to an array in the XML structure.
 * Link: http://www.bin-co.com/php/scripts/xml2array/
 * Arguments : $contents - The XML text
 *                $get_attributes - 1 or 0. If this is 1 the function will get the attributes as well as the tag values - this results in a different array structure in the return value.
 *                $priority - Can be 'tag' or 'attribute'. This will change the way the resulting array sturcture. For 'tag', the tags are given more importance.
 * Return: The parsed XML in an array form. Use print_r() to see the resulting array structure.
 * Examples: $array =  xml2array(file_get_contents('feed.xml'));
 *              $array =  xml2array(file_get_contents('feed.xml', 1, 'attribute'));
 */
function xml2array($contents, $get_attributes=1, $priority = 'tag') {
    if(!$contents) return array();

    if(!function_exists('xml_parser_create')) {
        //print "'xml_parser_create()' function not found!";
        return array();
    }

    //Get the XML parser of PHP - PHP must have this module for the parser to work
    $parser = xml_parser_create('');
    xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8"); # http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss
    xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
    xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
    xml_parse_into_struct($parser, trim($contents), $xml_values);
    xml_parser_free($parser);

    if(!$xml_values) return;//Hmm...

    //Initializations
    $xml_array = array();
    $parents = array();
    $opened_tags = array();
    $arr = array();

    $current = &$xml_array; //Refference

    //Go through the tags.
    $repeated_tag_index = array();//Multiple tags with same name will be turned into an array
    foreach($xml_values as $data) {
        unset($attributes,$value);//Remove existing values, or there will be trouble

        //This command will extract these variables into the foreach scope
        // tag(string), type(string), level(int), attributes(array).
        extract($data);//We could use the array by itself, but this cooler.

        $result = array();
        $attributes_data = array();
        
        if(isset($value)) {
            if($priority == 'tag') $result = $value;
            else $result['value'] = $value; //Put the value in a assoc array if we are in the 'Attribute' mode
        }

        //Set the attributes too.
        if(isset($attributes) and $get_attributes) {
            foreach($attributes as $attr => $val) {
                if($priority == 'tag') $attributes_data[$attr] = $val;
                else $result['attr'][$attr] = $val; //Set all the attributes in a array called 'attr'
            }
        }

        //See tag status and do the needed.
        if($type == "open") {//The starting of the tag '<tag>'
            $parent[$level-1] = &$current;
            if(!is_array($current) or (!in_array($tag, array_keys($current)))) { //Insert New tag
                $current[$tag] = $result;
                if($attributes_data) $current[$tag. '_attr'] = $attributes_data;
                $repeated_tag_index[$tag.'_'.$level] = 1;

                $current = &$current[$tag];

            } else { //There was another element with the same tag name

                if(isset($current[$tag][0])) {//If there is a 0th element it is already an array
                    $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
                    $repeated_tag_index[$tag.'_'.$level]++;
                } else {//This section will make the value an array if multiple tags with the same name appear together
                    $current[$tag] = array($current[$tag],$result);//This will combine the existing item and the new item together to make an array
                    $repeated_tag_index[$tag.'_'.$level] = 2;
                    
                    if(isset($current[$tag.'_attr'])) { //The attribute of the last(0th) tag must be moved as well
                        $current[$tag]['0_attr'] = $current[$tag.'_attr'];
                        unset($current[$tag.'_attr']);
                    }

                }
                $last_item_index = $repeated_tag_index[$tag.'_'.$level]-1;
                $current = &$current[$tag][$last_item_index];
            }

        } elseif($type == "complete") { //Tags that ends in 1 line '<tag />'
            //See if the key is already taken.
            if(!isset($current[$tag])) { //New Key
                $current[$tag] = $result;
                $repeated_tag_index[$tag.'_'.$level] = 1;
                if($priority == 'tag' and $attributes_data) $current[$tag. '_attr'] = $attributes_data;

            } else { //If taken, put all things inside a list(array)
                if(isset($current[$tag][0]) and is_array($current[$tag])) {//If it is already an array...

                    // ...push the new element into that array.
                    $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
                    
                    if($priority == 'tag' and $get_attributes and $attributes_data) {
                        $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
                    }
                    $repeated_tag_index[$tag.'_'.$level]++;

                } else { //If it is not an array...
                    $current[$tag] = array($current[$tag],$result); //...Make it an array using using the existing value and the new value
                    $repeated_tag_index[$tag.'_'.$level] = 1;
                    if($priority == 'tag' and $get_attributes) {
                        if(isset($current[$tag.'_attr'])) { //The attribute of the last(0th) tag must be moved as well
                            
                            $current[$tag]['0_attr'] = $current[$tag.'_attr'];
                            unset($current[$tag.'_attr']);
                        }
                        
                        if($attributes_data) {
                            $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
                        }
                    }
                    $repeated_tag_index[$tag.'_'.$level]++; //0 and 1 index is already taken
                }
            }

        } elseif($type == 'close') { //End of tag '</tag>'
            $current = &$parent[$level-1];
        }
    }
    
    return($xml_array);
}  
/* xml2array() will convert the given XML text to an array in the XML structure. */


/* array2json() will convert any given array into a json formatted string */
function array2json($arr) {
    if(function_exists('json_encode')) return json_encode($arr); //Lastest versions of PHP already has this functionality.
    $parts = array();
    $is_list = false;

    //Find out if the given array is a numerical array
    $keys = array_keys($arr);
    $max_length = count($arr)-1;
    if(($keys[0] == 0) and ($keys[$max_length] == $max_length)) {//See if the first key is 0 and last key is length - 1
        $is_list = true;
        for($i=0; $i<count($keys); $i++) { //See if each key correspondes to its position
            if($i != $keys[$i]) { //A key fails at position check.
                $is_list = false; //It is an associative array.
                break;
            }
        }
    }

    foreach($arr as $key=>$value) {
        if(is_array($value)) { //Custom handling for arrays
            if($is_list) $parts[] = array2json($value); /* :RECURSION: */
            else $parts[] = '"' . $key . '":' . array2json($value); /* :RECURSION: */
        } else {
            $str = '';
            if(!$is_list) $str = '"' . $key . '":';

            //Custom handling for multiple data types
            if(is_numeric($value)) $str .= $value; //Numbers
            elseif($value === false) $str .= 'false'; //The booleans
            elseif($value === true) $str .= 'true';
            else $str .= '"' . addslashes($value) . '"'; //All other things
            // :TODO: Is there any more datatype we should be in the lookout for? (Object?)

            $parts[] = $str;
        }
    }
    $json = implode(',',$parts);
    
    if($is_list) return '[' . $json . ']';//Return numerical JSON
    return '{' . $json . '}';//Return associative JSON
}
/* array2json() will convert any given array into a json formatted string */


function get_users_pod_id()
{
global $current_user;
get_currentuserinfo();
$user_wp_id = $current_user->ID;
$users = new Pod('users');
$users->page = 1;
$users->search = false;
$users->findRecords('id DESC',1,"wp_user.ID='$user_wp_id'");
while($users->fetchRecord())
{
$users_pod_id = $users->get_field('id');
}

return $users_pod_id; 
}

class arr2xml
{
	var $array = array();
	var $xml = '';

	function arr2xml($array)
	{
		$this->array = $array;
		
		if(is_array($array) && count($array) > 0)
		{
			$this->struct_xml($array);
		}
		else
		{
			$this->xml .= "no data";
		}
	}

	function struct_xml($array)
	{
		foreach($array as $k=>$v)
		{
			if(is_array($v))
			{
				$tag = ereg_replace('^[0-9]{1,}','data',$k); // replace numeric key in array to 'data'
				$this->xml .= "<$tag>";
				$this->struct_xml($v);
				$this->xml .= "</$tag>";
			}
			else
			{
				$tag = ereg_replace('^[0-9]{1,}','data',$k); // replace numeric key in array to 'data'
				$this->xml .= "<$tag>$v</$tag>";
			}
		}
	}
	
	function get_xml()
	{
		$header = "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?><root>";
		$footer = "</root>";
		
		echo $header;
		echo $this->xml;
		echo $footer;
	}
}
  
?>
